
package com.hulk.dryad.admin.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.enums.UseFlag;
import com.hulk.dryad.persistence.entity.SysPost;
import com.hulk.dryad.persistence.entity.SysUserPost;
import com.hulk.dryad.persistence.mapper.SysPostMapper;
import com.hulk.dryad.admin.service.SysPostService;

import com.hulk.dryad.manage.boot.injector.impl.DataScopeServiceImpl;

import com.hulk.dryad.admin.service.SysUserPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 岗位信息
 *
 * @author hulk
 * @date 2021-04-01 10:06:32
 */
@Service
@RequiredArgsConstructor
public class SysPostServiceImpl extends DataScopeServiceImpl<SysPostMapper, SysPost> implements SysPostService {

	private final SysUserPostService userPostService;

	@Override
	public List<SysPost> getListByUserId(Long userId) {
		// 获取关联列表
		List<SysUserPost> userPostList = userPostService.getListByUserId(userId);
		if (userPostList.isEmpty()) {
			return Collections.emptyList();
		}
		// 获取角色id列表
		Set<Long> postids = userPostList.stream()
				.map(SysUserPost::getPostId)
				.collect(Collectors.toSet());
		// 获取角色列表
		Wrapper<SysPost> wrapper = new LambdaQueryWrapper<SysPost>()
				.in(SysPost::getPostId, postids)
				.eq(SysPost::getUseFlag, UseFlag.YES.getValue());
		return super.list(wrapper);
	}

	@Override
	public boolean removePostByIds(Set<Long> ids) {
//		List<SysUserPost> userPostList = userPostService.getListByPostIds(ids);
//		if (userPostList != null && !userPostList.isEmpty()) {
//			throw new ServerRtException("存在用户岗位关系不能删除");
//		}
		userPostService.removeByPostIds(ids);
		return super.removeByIds(ids);
	}

	@Override
	@Cacheable(value = CacheConstants.POST_DETAILS + "#60s", unless = "#result == null")
	public List<SysPost> getAllPosts() {
		LambdaQueryWrapper<SysPost> qw = Wrappers.<SysPost>lambdaQuery().eq(SysPost::getUseFlag, UseFlag.YES.getValue());
		List<SysPost> models =super.list(qw);
		return models;
	}

	@Override
	@Cacheable(value = CacheConstants.POST_ID_DETAILS + "#60s", unless = "#result == null")
	public Set<Long> getAllPostIds() {
		Set<Long> postIds = this.getAllPosts().stream().map(SysPost::getPostId).collect(Collectors.toSet());
		return postIds;
	}

}
